package com.hbnu;

import com.hbnu.Service.CartService;
import com.hbnu.Service.OrderService;
import com.hbnu.Service.ProductService;
import com.hbnu.Service.UserService;
import com.hbnu.pojo.*;
import com.hbnu.util.InputUtil;

import java.math.BigDecimal;
import java.util.List;

public class Test {
    private static UserService userService = new UserService();
    private static ProductService productService = new ProductService();
    private static CartService cartService = new CartService();
    private static User currentUser = null;

    public static void main(String[] args) {
        showMainMenu();
    }

    private static void showMainMenu() {
        while (true) {
            System.out.println("\n===== 便利店在线购物系统 =====");
            System.out.println("1. 用户登录");
            System.out.println("2. 用户注册");
            System.out.println("3. 退出系统");
            System.out.println("============================");

            int choice = InputUtil.getIntInput("请选择操作: ");

            switch (choice) {
                case 1:
                    login();
                    break;
                case 2:
                    register();
                    break;
                case 3:
                    System.out.println("感谢使用，再见！");
                    return;
                default:
                    System.out.println("无效选择，请重新输入！");
            }
        }
    }

    private static void login() {
        System.out.println("\n----- 用户登录 -----");
        String username = InputUtil.getStringInput("用户名: ");
        String password = InputUtil.getStringInput("密码: ");

        currentUser = userService.login(username, password);
        if (currentUser != null) {
            System.out.println("登录成功！欢迎，" + currentUser.getUsername());
            showUserMenu();
        } else {
            System.out.println("登录失败！用户名或密码错误。");
        }
    }

    private static void register() {
        System.out.println("\n----- 用户注册 -----");
        String username = InputUtil.getStringInput("用户名: ");
        String password = InputUtil.getStringInput("密码: ");
        String phone = InputUtil.getStringInput("手机号: ");
        String address = InputUtil.getStringInput("地址: ");

        User newUser = new User();
        newUser.setUsername(username);
        newUser.setPassword(password);
        newUser.setPhone(phone);
        newUser.setAddress(address);
        if (userService.register(newUser)) {
            System.out.println("注册成功！请登录。");
        } else {
            System.out.println("注册失败！用户名可能已存在。");
        }
    }

    private static void showUserMenu() {
        while (currentUser != null) {
            System.out.println("\n===== 用户菜单 =====");
            System.out.println("欢迎，" + currentUser.getUsername());
            System.out.println("余额: ￥" + currentUser.getBalance());
            System.out.println("1. 浏览商品");
            System.out.println("2. 查看购物车");
            System.out.println("3. 充值");
            System.out.println("4. 查看订单");
            System.out.println("5. 退出登录");
            System.out.println("====================");

            int choice = InputUtil.getIntInput("请选择操作: ");

            switch (choice) {
                case 1:
                    browseProducts();
                    break;
                case 2:
                    viewCart();
                    break;
                case 3:
                    recharge();
                    break;
                case 4:
                    viewOrders();
                    break;
                case 5:
                    currentUser = null;
                    System.out.println("已退出登录！");
                    return;
                default:
                    System.out.println("无效选择，请重新输入！");
            }
        }
    }

    private static void browseProducts() {
        List<Product> products = productService.getAllProducts();

        System.out.println("\n----- 商品列表 -----");
        if (products.isEmpty()) {
            System.out.println("暂无商品！");
            return;
        }

        for (int i = 0; i < products.size(); i++) {
            Product product = products.get(i);
            System.out.printf("%d. %s - ￥%.2f (库存: %d)%n",
                    i + 1, product.getName(), product.getPrice(), product.getStock());
            System.out.println("   描述: " + product.getDescription());
        }

        int choice = InputUtil.getIntInput("选择商品编号查看详情 (0返回): ");
        if (choice == 0) return;

        if (choice > 0 && choice <= products.size()) {
            Product selectedProduct = products.get(choice - 1);
            viewProductDetail(selectedProduct);
        } else {
            System.out.println("无效选择！");
        }
    }

    private static void viewProductDetail(Product product) {
        System.out.println("\n----- 商品详情 -----");
        System.out.println("名称: " + product.getName());
        System.out.println("描述: " + product.getDescription());
        System.out.printf("价格: ￥%.2f%n", product.getPrice());
        System.out.println("库存: " + product.getStock());
        System.out.println("分类: " + product.getCategory());

        System.out.println("\n1. 加入购物车");
        System.out.println("2. 返回商品列表");

        int choice = InputUtil.getIntInput("请选择操作: ");

        if (choice == 1) {
            int quantity = InputUtil.getIntInput("请输入购买数量: ");
            if (quantity > 0 && quantity <= product.getStock()) {
                if (cartService.addToCart(currentUser.getId(), product.getId(), quantity)) {
                    System.out.println("成功加入购物车！");
                } else {
                    System.out.println("加入购物车失败！");
                }
            } else {
                System.out.println("库存不足或数量无效！");
            }
        }
    }

    private static void viewCart() {
        List<CartItem> cartItems = cartService.getCartItems(currentUser.getId());

        System.out.println("\n----- 购物车 -----");
        if (cartItems.isEmpty()) {
            System.out.println("购物车为空！");
            return;
        }

        BigDecimal total = BigDecimal.ZERO;
        for (int i = 0; i < cartItems.size(); i++) {
            CartItem item = cartItems.get(i);
            BigDecimal itemTotal = item.getProduct().getPrice().multiply(BigDecimal.valueOf(item.getQuantity()));
            total = total.add(itemTotal);

            System.out.printf("%d. %s - ￥%.2f × %d = ￥%.2f%n",
                    i + 1, item.getProduct().getName(),
                    item.getProduct().getPrice(), item.getQuantity(), itemTotal);
        }
        System.out.printf("总计: ￥%.2f%n", total);

        System.out.println("\n1. 结算订单");
        System.out.println("2. 移除商品");
        System.out.println("3. 清空购物车");
        System.out.println("4. 返回");

        int choice = InputUtil.getIntInput("请选择操作: ");

        switch (choice) {
            case 1:
                checkout(total);
                break;
            case 2:
                removeFromCart(cartItems);
                break;
            case 3:
                if (cartService.clearCart(currentUser.getId())) {
                    System.out.println("购物车已清空！");
                } else {
                    System.out.println("清空购物车失败！");
                }
                break;
            case 4:
                return;
            default:
                System.out.println("无效选择！");
        }
    }
//-------------------------------------------------------------------------------------
    private static void checkout(BigDecimal total) {
        if (currentUser.getBalance().compareTo(total) < 0) {
            System.out.println("余额不足！当前余额: ￥" + currentUser.getBalance() + "，需要: ￥" + total);
            return;
        }

        // 获取购物车商品
        List<CartItem> cartItems = cartService.getCartItems(currentUser.getId());
        if (cartItems.isEmpty()) {
            System.out.println("购物车为空，无法结算！");
            return;
        }

        // 确认订单
        System.out.println("\n----- 订单确认 -----");
        System.out.println("订单总金额: ￥" + total);
        System.out.println("收货地址: " + currentUser.getAddress());

        String confirm = InputUtil.getStringInput("确认下单？(y/n): ");
        if (!confirm.equalsIgnoreCase("y")) {
            System.out.println("已取消下单！");
            return;
        }

        // 创建订单服务
        OrderService orderService = new OrderService();

        // 创建订单
        if (orderService.createOrder(currentUser.getId(), cartItems, total)) {
            // 扣减余额
            BigDecimal newBalance = currentUser.getBalance().subtract(total);
            if (userService.updateBalance(currentUser.getId(), newBalance)) {
                currentUser.setBalance(newBalance);

                // 清空购物车
                cartService.clearCart(currentUser.getId());

                System.out.println("订单创建成功！总金额: ￥" + total);
                System.out.println("余额已扣除，当前余额: ￥" + currentUser.getBalance());
            } else {
                System.out.println("扣款失败！");
            }
        } else {
            System.out.println("订单创建失败！");
        }
    }

    private static void removeFromCart(List<CartItem> cartItems) {
        int choice = InputUtil.getIntInput("请输入要移除的商品编号: ");
        if (choice > 0 && choice <= cartItems.size()) {
            CartItem item = cartItems.get(choice - 1);
            if (cartService.removeFromCart(item.getId())) {
                System.out.println("商品已从购物车移除！");
            } else {
                System.out.println("移除失败！");
            }
        } else {
            System.out.println("无效选择！");
        }
    }

    //-----------------------------------------------------------------
    private static void recharge() {
        double amount = InputUtil.getDoubleInput("请输入充值金额: ");
        if (amount <= 0) {
            System.out.println("充值金额必须大于0！");
            return;
        }

        BigDecimal newBalance = currentUser.getBalance().add(BigDecimal.valueOf(amount));
        if (userService.recharge(currentUser.getId(), newBalance)) {
            currentUser.setBalance(newBalance);
            System.out.println("充值成功！当前余额: ￥" + currentUser.getBalance());
        } else {
            System.out.println("充值失败！");
        }
    }


    private static void viewOrders() {
        OrderService orderService = new OrderService();
        List<Order> orders = orderService.getOrdersByUserId(currentUser.getId());

        System.out.println("\n----- 我的订单 -----");
        if (orders.isEmpty()) {
            System.out.println("暂无订单！");
            return;
        }

        for (int i = 0; i < orders.size(); i++) {
            Order order = orders.get(i);
            System.out.printf("%d. 订单号: %d | 总金额: ￥%.2f | 状态: %s | 时间: %s%n",
                    i + 1, order.getId(), order.getTotalAmount(),
                    getStatusText(order.getStatus()), order.getCreatedTime());
        }

        int choice = InputUtil.getIntInput("选择订单查看详情 (0返回): ");
        if (choice == 0) return;

        if (choice > 0 && choice <= orders.size()) {
            Order selectedOrder = orders.get(choice - 1);
            viewOrderDetail(selectedOrder);
        } else {
            System.out.println("无效选择！");
        }
    }

    private static void viewOrderDetail(Order order) {
        System.out.println("\n----- 订单详情 -----");
        System.out.println("订单号: " + order.getId());
        System.out.printf("总金额: ￥%.2f%n", order.getTotalAmount());
        System.out.println("状态: " + getStatusText(order.getStatus()));
        System.out.println("下单时间: " + order.getCreatedTime());
        System.out.println("收货地址: " + currentUser.getAddress());

        System.out.println("\n订单商品:");
        if (order.getItems() != null && !order.getItems().isEmpty()) {
            for (OrderItem item : order.getItems()) {
                System.out.printf("  %s - ￥%.2f × %d = ￥%.2f%n",
                        item.getProduct().getName(), item.getPrice(),
                        item.getQuantity(), item.getPrice().multiply(BigDecimal.valueOf(item.getQuantity())));
            }
        } else {
            System.out.println("  暂无商品信息");
        }

        // 如果是待支付订单，可以在这里添加支付功能
        if ("pending".equals(order.getStatus())) {
            System.out.println("\n1. 立即支付");
            System.out.println("2. 返回");

            int choice = InputUtil.getIntInput("请选择操作: ");
            if (choice == 1) {
                payOrder(order);
            }
        } else {
            InputUtil.getStringInput("按回车键返回...");
        }
    }

    private static void payOrder(Order order) {
        if (currentUser.getBalance().compareTo(order.getTotalAmount()) < 0) {
            System.out.println("余额不足！当前余额: ￥" + currentUser.getBalance() + "，需要: ￥" + order.getTotalAmount());
            return;
        }

        OrderService orderService = new OrderService();
        if (orderService.completeOrder(order.getId(), currentUser.getId(), order.getTotalAmount())) {
            // 扣减余额
            BigDecimal newBalance = currentUser.getBalance().subtract(order.getTotalAmount());
            if (userService.updateBalance(currentUser.getId(), newBalance)) {
                currentUser.setBalance(newBalance);
                System.out.println("支付成功！订单已完成。");
                System.out.println("余额已扣除，当前余额: ￥" + currentUser.getBalance());

                // 更新订单状态
                order.setStatus("completed");
            } else {
                System.out.println("扣款失败！");
            }
        } else {
            System.out.println("支付失败！");
        }
    }

    private static String getStatusText(String status) {
        switch (status) {
            case "pending": return "待支付";
            case "completed": return "已完成";
            case "cancelled": return "已取消";
            default: return status;
        }
    }


}
